package com.first.nell.loan

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.first.nell.base.BaseFragment
import com.first.nell.components.dialog.AppReviewActiveDialog
import com.first.nell.components.dialog.AppReviewDialog
import com.first.nell.data.ReqBase
import com.first.nell.databinding.FragmentFirstNellLoanLoaningBinding
import com.first.nell.enums.PageTagEnum
import com.first.nell.extend.*
import com.first.nell.info.cotediva.WalletInfoViewModel
import com.first.nell.launch.UserStateViewModel
import com.first.nell.loan.adapter.ReviewWalletListAdapter
import com.first.nell.utils.SpUtil
import com.first.nell.utils.UsageCountryUtil
import com.first.nell.utils.analytics.util.AnalyticsUtil


/** 放款中 */
class LoanLoaningFragment : BaseFragment() {

    //布局binding
    private lateinit var mFragmentBinding: FragmentFirstNellLoanLoaningBinding

    //科特钱包适配器
    private lateinit var mWalletListFcfaAdapter: ReviewWalletListAdapter

    //贷款viewModel
    private val mLoanViewModel by lazy {
        ViewModelProvider(this).get(LoanViewModel::class.java)
    }

    //科特钱包viewModel
    private val mWalletInfoViewModel by lazy {
        ViewModelProvider(this)[WalletInfoViewModel::class.java]
    }

    //用户流程viewModel
    private val mUserStateViewModel by lazy {
        ViewModelProvider(this).get(UserStateViewModel::class.java)
    }

    override fun onFirstNellBindingFirstNellViewFirstNellModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mWalletInfoViewModel)
        list.add(mLoanViewModel)
        list.add(mUserStateViewModel)
        return list
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        mFragmentBinding = FragmentFirstNellLoanLoaningBinding.inflate(inflater, container, false)
        return mFragmentBinding.root
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        try {
            //初始化列表
            mWalletListFcfaAdapter =
                ReviewWalletListAdapter(mWalletInfoViewModel.mFirstNellWalletFirstNellList)
            mFragmentBinding.rcLoaningWalletListFcfa.layoutManager =
                LinearLayoutManager(requireActivity())
            mFragmentBinding.rcLoaningWalletListFcfa.adapter = mWalletListFcfaAdapter

            //获取用户状态回调
            mUserStateViewModel.onFirstNellFetchFirstNellUserFirstNellStateFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isSuccess) {
                    try {
                        //刷新流程
                        startFirstNellToFirstNellNextFirstNellFromFirstNellPage(PageTagEnum.loaning)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }

            //获取放款信息回调
            mLoanViewModel.onFirstNellFetchFirstNellLoaningFirstNellDetailFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        //更新页面显示
                        mFragmentBinding.textLoaningLoanAmountValue.text =
                            result.currency + " " + result.displayFirstNellAmount()

                        mFragmentBinding.textLoaningLoanTermValue.text =
                            result.displayFirstNellDays().toFirstNellDaysFirstNellSuffix()

                        mFragmentBinding.textLoaningReceiveAccountValue.text =
                            result.bankAccount.safeFirstNellString()
                    }
                }
            }

            //获取用户钱包列表回调
            mWalletInfoViewModel.onFirstNellFetchFirstNellWalletFirstNellListFirstNellFCFAFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        result.forEach { item ->
                            item.displayMode = 2
                        }
                        mWalletInfoViewModel.initFirstNellWalletFirstNellListFirstNellFCFA(
                            result
                        )
                        mWalletListFcfaAdapter.notifyDataSetChanged()
                    }
                }
            }

            //获取app评介流程回调
            mLoanViewModel.onCheckFirstNellAppFirstNellReviewFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        if (result.activeWindow?.switch?.equals("YES", true) == true) {
                            val count =
                                SpUtil.getFirstNellAppFirstNellReviewFirstNellActive()
                            val num = (result.activeWindow?.num) ?: 3
                            if (count < num) {
                                AppReviewActiveDialog.showFirstNellDialog(
                                    fragmentManager = requireActivity().supportFragmentManager,
                                    result.activeWindow?.content
                                )
                                SpUtil.saveFirstNellAppFirstNellReviewFirstNellActive(
                                    (count + 1)
                                )
                                try {
                                    AnalyticsUtil.saveHitPointInfo(
                                        type = "APP_REVIEW_ACTIVE_SHOW",
                                        remark = count.toString()
                                    )
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }

                        } else if (result.normalWindow?.switch?.equals("YES", true) == true) {
                            val count =
                                SpUtil.getFirstNellAppFirstNellReviewFirstNellNormal()
                            val num = (result.normalWindow?.num) ?: 3
                            if (count < num) {
                                AppReviewDialog.showFirstNellDialog(
                                    fragmentManager = requireActivity().supportFragmentManager,
                                    result.normalWindow?.content
                                )
                                SpUtil.saveFirstNellAppFirstNellReviewFirstNellNormal(
                                    (count + 1)
                                )
                                try {
                                    AnalyticsUtil.saveHitPointInfo(
                                        type = "APP_REVIEW_NORMAL_SHOW",
                                        remark = count.toString()
                                    )
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                    }
                }
            }

            //点击刷新
            mFragmentBinding.submitLoanLoaning.setOnClickListener {
                //记录埋点
                mFragmentBinding.submitLoanLoaning.recordFirstNellEvent(
                    type = mFragmentBinding.submitLoanLoaning.getFirstNellScenFirstNellClickFirstNellFlag(
                        PageTagEnum.review.name.uppercase()
                    ),
                    remark = ""
                )
                //查询用户状态
                mUserStateViewModel.fetchFirstNellUserFirstNellState()
            }

            //区分科特与其它地区的收款账号显示
            mFragmentBinding.llLoaningReceiveAccountBg.visibility = View.VISIBLE
            mFragmentBinding.rlLoaningReceiveAccountBgFcfa.visibility = View.GONE
            if (UsageCountryUtil.isFirstNellCountryFirstNellCotediva()) {
                mFragmentBinding.llLoaningReceiveAccountBg.visibility = View.GONE
                mFragmentBinding.rlLoaningReceiveAccountBgFcfa.visibility = View.VISIBLE
            }
            if (UsageCountryUtil.isFirstNellCountryFirstNellXaf()) {
                mFragmentBinding.llLoaningReceiveAccountBg.visibility = View.GONE
                mFragmentBinding.rlLoaningReceiveAccountBgFcfa.visibility = View.VISIBLE
            }

            //获取放款信息
            mLoanViewModel.fetchFirstNellLoaningFirstNellDetail(ReqBase())

            //如果是科特，需要获取钱包列表
            if (UsageCountryUtil.isFirstNellCountryFirstNellCotediva() || UsageCountryUtil.isFirstNellCountryFirstNellXaf()) {
                //获取钱包列表
                mWalletInfoViewModel.getFirstNellWalletFirstNellListFirstNellFCFA()
            }

            //查询是否需要弹框
            mLoanViewModel.checkFirstNellAppFirstNellReview(ReqBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}